package com.le.tester.javaThink.fourth.concurrency;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.SynchronousQueue;

/**
 * createTime：2021/12/16 17:14
 * description：将生产的消息放进阻塞的队列中，然后检测system.in来
 */

//将消息放进队列
class LiftOffRunner implements Runnable {

    private BlockingQueue<LiftOff> rockets;

    public LiftOffRunner(BlockingQueue<LiftOff> rockets) {
        this.rockets = rockets;
    }

    public void add(LiftOff lo) {
        try {
            rockets.put(lo);
        } catch (InterruptedException e) {
            System.out.println("Interrupted during put()");
        }
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                LiftOff take = rockets.take();
                take.run();
            }
        } catch (Exception e) {
            System.out.println("Waiting from take()");
        }
        System.out.println("Exiting LiftOffRunner");
    }
}

public class TestBlockingQueues {
    static void getKey() {
        try {
            new BufferedReader(new InputStreamReader(System.in)).readLine();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    static void getKey(String message) {
        System.out.println(message);
        getKey();
    }

    static void test(String msg, BlockingQueue<LiftOff> queue) {
        System.out.println(msg);
        LiftOffRunner liftOffRunner = new LiftOffRunner(queue);
        Thread thread = new Thread(liftOffRunner);
        thread.start();
        for (int i = 0; i < 5; i++) {
            //放进阻塞队列中(循环5次)
            liftOffRunner.add(new LiftOff(5));
        }
        //读取键盘输入信息
        getKey("Press Enter " + msg + ".");
        thread.interrupt();
        System.out.println("Finished " + msg + " test");
    }

    public static void main(String[] args) {
        //链表中的阻塞队列
        test("LinkedBlockingQueue", new LinkedBlockingDeque<>());
        System.out.println("linkedBlockingQueue==================");
        //false设置成不阻塞(设置成不公平锁)，即不阻塞
        test("ArrayBlockingQueue", new ArrayBlockingQueue<>(3, false));
        System.out.println("ArrayBlockingQueue==================");
        //默认的不公平锁，不会阻塞
        test("SynchronousQueue", new SynchronousQueue<>());
    }
}
